from torchvision.utils import make_grid

def filter_out_meaningful_features(feature,batch_id,alpha=0.05):
    print(feature.shape)
    differences = (feature[batch_id].view(feature[batch_id].shape[0],-1).max(dim=-1).values \
        -  feature[batch_id].view(feature[batch_id].shape[0],-1).min(dim=-1).values)
    print(differences.shape)
    threshold  = (differences.max()-differences.min())*alpha+differences.min()
    meaningful_idx = differences.abs()> threshold
    return feature[batch_id][meaningful_idx]

def draw_cnn_feature(feature,batch_id=0,nrow=16,filter_out_blank_feature=False):
    if filter_out_blank_feature:
        filtered_feature= filter_out_meaningful_features(feature,batch_id) #过滤全黑的卷积激活
    else:
        filtered_feature = feature[batch_id] #不过滤全黑的卷积激活
    grid = make_grid( 
        filtered_feature.unsqueeze(1).abs(),
        nrow=nrow,
        padding=1,
        pad_value=1.,
        normalize=True
        ).cpu().numpy().transpose(1,2,0)
    return grid